<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>VUE实现无限滚动demo2</title>
    <style>
        .box {
            width: 100%;
            text-align: center;
            vertical-align: middle;
            border: 1px solid #777;
            height: 200px;
            font-size: 24px;
        }
    </style>
</head>
<body>
<div id="app">
    <div v-for="d in view" class="box">
        {{d}}
    </div>
</div>
<script src="https://cdn.staticfile.org/vue/2.5.22/vue.js"></script>
<script>
    /**
     * demo2
     * 在 demo1 上进行改进
     * 解决了向下滚动加载时，减少顶部dom
     * 并增加顶部padding来撑住滚动条
     * 可以实现无感的向下滚动
     * 余下需要解决的是，用于如果先滚动到中间，再往上或者往下滚动的情况
     */
    let vm = new Vue({
        el: '#app',
        data: {
            size: 10,
            page: 0,
            view: [],
            back: []
        },
        methods: {
            initView: function () {
                console.log(
                    'page = ' + this.page
                )
                this.view.push(...this.back.slice(
                    this.page * this.size,
                    (this.page + 1) * this.size
                ));
                if(this.page > 1){
                    this.view.splice(0,this.size)
                    document.querySelector('#app').style.paddingTop = (200 * (this.page - 1) * this.size) + 'px'
                }
            }
        },
        created: function () {
            window.onscroll = function () {
                const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
                const windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
                const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
                console.log(
                    'scrollTop = ' + scrollTop + ' windowHeight = ' + windowHeight + '  scrollHeight = ' + scrollHeight
                );
                if (scrollTop + windowHeight >= scrollHeight - windowHeight) {
                    vm.page++;
                    vm.initView();
                }
            };
        },
        mounted: function () {
            for (let i = 0; i < 10000; i++) {
                this.back.push(i);
            }
            this.initView();
        }
    });
</script>
</body>
</html>